//
// Forward declare functions
//

var findStatementAnchor;
var getStatementUrl;


function handleStatementsAndDocumentsPage(page)
{
    var d = new Date();
    var currentMonth = d.getMonth();
    var lastMonth = currentMonth - 1;
    var monthName = getMonthAsName(lastMonth);
    var year = d.getFullYear();
   
    var anchors = document.getElementsByTagName('a');
    var statementAnchor = findStatementAnchor(anchors, monthName, year);
    
    if (null != statementAnchor)
    {
        var qpvalues = getQueryParameters(statementAnchor.href);
        var accountId = qpvalues[QUERYPARAMETER_ACCOUNT_IDENTITIFIER_ALT];
        var optionId = qpvalues[QUERYPARAMETER_OPTION_ID];
        var hash = qpvalues[QUERYPARAMETER_HASH];

        debugLog('accountId = ' + accountId);
        debugLog('optionId = ' + optionId);
        debugLog('hash = ' + hash);
        
        var statementUrl = getStatementUrl(accountId, optionId, hash);

        debugLog('statementUrl = ' + statementUrl);
        
        if (null != statementUrl)
        {
            window.location = statementUrl;
        }
    }
}

function findStatementAnchor(anchors, month, year)
{
    debugLog('findStatementAnchor(' + anchors + ', ' + month + ', ' + year +')');
    
    var foundAnchor = null;

    // June 07, 2011 
    var regex = new RegExp(month + '\\s+\\d+,\\s+' + year, 'i');
    
    debugLog(regex);
    debugLog('anchors = ' + anchors);
    
    for (var index = 0; index < anchors.length; index++)
    {
        if (regex.test(anchors[index].innerText))
        {
            assert((null == foundAnchor), 'Unexpectedly found more than one match');
            foundAnchor = anchors[index];
        }
    }
    
    return foundAnchor;
}

function getStatementUrl(accountId, optionId, hash)
{
    // It is possible that it is not important to have the correct
    // values for the 'OptedForPaperless' and 'EligibleForPaperless'
    // In that case set them to the values that are least likely to
    // cause follow-up prompts/pages 
    var optedForPaperless = 'True';
    var eligibleForPaperless = 'True';

    return STATEMENT_PAGE_BASE_URL + '?AccountId=' + accountId
                                   + '&OptionId=' + optionId
                                   + '&OptedForPaperless=' + optedForPaperless
                                   + '&EligibleForPaperless=' + eligibleForPaperless
                                   + '&Hash=' + hash;
}
